<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <NewPageFilter
      v-model:query="filterInfo.query.queryMap"
      :query-more-json="false"
      :filter-list="filterInfo.searchList"
      :filter-btn="filterInfo.searchBtn"
      :list-type-info="listTypeInfo"
      :clear-type="clearType"
    >
      <template v-slot:filter-operateTime>
        <el-date-picker
          @change="timeChange"
          v-model="operateTime"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          align="right"
          :shortcuts="$fn.pickerOptionsFn()"
          start-placeholder="操作时间开始日期"
          end-placeholder="操作时间结束日期"
          :default-time="[
            new Date(2000, 1, 1, 0, 0, 0),
            new Date(2000, 1, 1, 23, 59, 59),
          ]"
        ></el-date-picker>
      </template>
    </NewPageFilter>
    <div class="filter-wrapper">
      <NewPageFilter :filter-btn="filterInfo.btnList"> </NewPageFilter>
    </div>

    <!-- 表格 -->
    <TableContainer
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="tableInfo.api"
      :summary="true"
      :summaryFieldList="tableInfo.summaryFieldList"
      :allSummary="true"
      :allSummaryData="allSummaryData"
      :tab-index="true"
      :check-box="false"
      v-model:query="filterInfo.query.queryMap"
      :field-list="tableInfo.fieldList"
      @handleEvent="handleEvent"
      @pageInfo="pageInfo"
      @sortChange="sortChange"
    >
    </TableContainer>

    <PageDialog
      v-if="dialogTipsInfo.visible"
      :title="dialogTipsInfo.title"
      v-model:visible="dialogTipsInfo.visible"
      :width="dialogTipsInfo.width"
      :bt-loading="dialogTipsInfo.btLoading"
      :bt-list="dialogTipsInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogTipsInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogTipsInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </PageDialog>
  </div>
</template>

<script setup name="warehousingDetails">
import { ElMessage } from 'element-plus'
import {
  getWarehousingDetails,
  printWarehousingDetails,
  warehousingDetailsExcel,
} from '@/api/statisticalReports'
import { fatchTemplateByCode } from '@/api/base'
import utils from '@/common/js/utils'
import moment from 'moment'
import { getDepotAll, getSupplierAll } from '@/api/core'

const { proxy } = getCurrentInstance()
const clearType = ref(true)
const groupFlag = ref(false)
const allSummaryData = ref({
  data: [],
  fieldList: [
    {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
})
const listTypeInfo = ref({
  depotList: [],
  supplierList: [],
})

const filterInfo = ref({
  sortArr: [],
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      operateTimeStart: moment(
        new Date(new Date().getTime() - 3600 * 1000 * 24 * 90)
      ).format('YYYY-MM-DD HH:mm:ss'),
      operateTimeEnd: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
    },
    copyQueryMap: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '打印',
      event: print,
      show: proxy.$permission('warehousingDetails:print'),
    },
    {
      type: 'button',
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('warehousingDetails:excel'),
    },
  ],
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  summaryFieldList: [
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [],
  },
})
const dialogTipsInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const operateTime = ref([
  moment(new Date(new Date().getTime() - 3600 * 1000 * 24 * 90)).format(
    'YYYY-MM-DD HH:mm:ss'
  ),
  moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
])
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
function updateGroupSelections(arr) {
  filterInfo.value.query.groups = arr
  groupSelectInfo.value.selections = arr
  if (!arr.length) {
    filterInfo.value.query.groups = []
    filterInfo.value.query.groupMap = {}
    groupSelectInfo.value.data = []
    groupFlag.value = false
  }
}

function sortChange(column) {
  let arr = proxy.$fn.sortChange(column, [], ' ')
  filterInfo.value.sortArr = arr
  filterInfo.value.query.queryMap.sort = arr.toString()
  search()
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}

function getCustomize() {
  tableInfo.value.api = getWarehousingDetails
  getList()
  initDepotList()
  initSupplierSelect()
}
function getList() {
  tableInfo.value.refresh = Math.random()
}
function search() {
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  operateTime.value = [
    moment(new Date(new Date().getTime() - 3600 * 1000 * 24 * 90)).format(
      'YYYY-MM-DD HH:mm:ss'
    ),
    moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
  ]
  search()
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.queryMap.operateTimeStart = val[0]
    filterInfo.value.query.queryMap.operateTimeEnd = val[1]
  } else {
    filterInfo.value.query.queryMap.operateTimeStart = null
    filterInfo.value.query.queryMap.operateTimeEnd = null
  }
}
function handleClose() {
  dialogTipsInfo.value.visible = false
}
function print() {
  //打印
  dialogTipsInfo.value.visible = true
  dialogTipsInfo.value.type = 'print'
  dialogTipsInfo.value.msg = '请选择当数据打印范围'
  dialogTipsInfo.value.btList[1].label = '打印'
  dialogTipsInfo.value.flag = true
}
//打印导出
function pageInfo(obj) {
  page.value = obj
}
function exportExcel() {
  //导出
  dialogTipsInfo.value.visible = true
  dialogTipsInfo.value.type = 'excel'
  dialogTipsInfo.value.msg = '请选择数据导出范围'
  dialogTipsInfo.value.btList[1].label = '导出'
  dialogTipsInfo.value.flag = true
}
function checkConfirm() {
  if (dialogTipsInfo.value.type === 'excel') {
    exportExcelList()
  } else if (dialogTipsInfo.value.type === 'print') {
    printList()
  }
  dialogTipsInfo.value.visible = false
  dialogTipsInfo.value.msg = ''
}
function printList() {
  if (operateTime.value) {
    let startTime =
      typeof operateTime.value[0] === 'string'
        ? new Date(operateTime.value[0])
        : operateTime.value[0]
    let endTime =
      typeof operateTime.value[1] === 'string'
        ? new Date(operateTime.value[1])
        : operateTime.value[1]
    if (endTime.getTime() - startTime.getTime() > 3600 * 1000 * 24 * 365) {
      proxy.$message.warning('操作时间间隔不能超过一年！')
    } else {
      fatchTemplateByCode({
        resourceCode: 'warehousingDetails:print',
        isDefault: 1,
      }).then((res) => {
        if (res && res.success) {
          let temp = proxy.$fn.getPrintTemp(res.data[0])
          getPrintData(temp)
        }
      })
    }
  } else {
    proxy.$message.warning('请选择操作时间')
  }
}
function getPrintData(temp) {
  let params = {
    ...filterInfo.value.query.queryMap,
    ...page.value,
    page: dialogTipsInfo.value.flag,
  }
  printWarehousingDetails(params).then((resp) => {
    if (resp && resp.success) {
      let data = proxy.$fn.deepClone(resp.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function exportExcelList() {
  if (operateTime.value) {
    let startTime =
      typeof operateTime.value[0] === 'string'
        ? new Date(operateTime.value[0])
        : operateTime.value[0]
    let endTime =
      typeof operateTime.value[1] === 'string'
        ? new Date(operateTime.value[1])
        : operateTime.value[1]
    if (endTime.getTime() - startTime.getTime() > 3600 * 1000 * 24 * 365) {
      proxy.$message.warning('操作时间间隔不能超过一年！')
    } else {
      let params = {
        ...filterInfo.value.query.queryMap,
        ...page.value,
        page: dialogTipsInfo.value.flag,
      }
      warehousingDetailsExcel(params).then((resp) => {
        if (resp) {
          proxy.$fn.parseExcel(resp)
        }
      })
    }
  } else {
    proxy.$message.warning('请选择操作时间')
  }
}

function initDepotList() {
  const params = {
    depotAuth: 'id',
  }
  getDepotAll(params).then((resp) => {
    if (resp && resp.success) {
      listTypeInfo.value.depotList = resp.data.map((item) => {
        return {
          key: item.name,
          value: item.id,
        }
      })
    }
  })
}
function initSupplierSelect() {
  const params = {
    supplierAuth: 'supplierId',
  }
  getSupplierAll(params).then((resp) => {
    if (resp && resp.success) {
      listTypeInfo.value.supplierList = resp.data.map((item) => {
        return {
          key: item.supplierName,
          value: item.supplierId,
        }
      })
    }
  })
}

let obj = {
  typeValue: {
    label: '操作类型',
    value: 'typeValue',
    asValue: 'type',
    type: 'column',
    componentType: 'select-model',
    code: 'store_affair_type',
    hidden: false,
    show: false,
  },
  reagent: {
    label: '类型',
    value: 'reagent',
    formatter: proxy.$fn.TripartiteMethod,
    type: 'text',
    componentType: 'input',
    event: search,
    hidden: false,
    show: false,
  },
  depotId: {
    label: '仓库',
    value: 'depotId',
    // type: "column",
    componentType: 'select',
    list: 'depotList',
    event: search,
    hidden: true,
    show: true,
  },
  depotName: {
    label: '仓库',
    value: 'depotName',
    formatter: proxy.$fn.TripartiteMethod,
    type: 'text',
    event: search,
    hidden: false,
    sortable: 'custom',
    show: false,
  },
  supplierName: {
    label: '供应商',
    value: 'supplierName',
    asValue: 'supplierId',
    componentType: 'select',
    list: 'supplierList',
    hidden: false,
    sortable: 'custom',
    show: true,
    event: search,
    clearable: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    type: 'column',
    componentType: 'price',
    hidden: false,
    sortable: 'custom',
    show: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  operateTime: {
    label: '操作时间',
    value: 'operateTime',
    componentType: 'dateTime',
    event: search,
    slot: true,
    hidden: false,
    show: true,
  },
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
</script>

<style scoped></style>
